package com.jiabowen.store.controller;

import ch.qos.logback.core.util.FileSize;
import com.jiabowen.store.controller.exception.*;
import com.jiabowen.store.entity.User;
import com.jiabowen.store.service.IUserService;
import com.jiabowen.store.service.exception.InsertException;
import com.jiabowen.store.service.exception.UsernameDuplicatedException;
import com.jiabowen.store.service.impl.UserServiceImpl;
import com.jiabowen.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.security.x509.DeltaCRLIndicatorExtension;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController//@Controller + @ResponseBody
@RequestMapping("users")
public class UserController extends BaseController {

    @Autowired
    private IUserService iUserService;

    /**
     * 重新构建reg()
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        iUserService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session) {
        User data = iUserService.login(username, password);

        // 向session对象中完成数据的绑定（session全局的）
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());

        //获取session中绑定的数据
        System.out.println(getUidFromSession(session));
        System.out.println(getUsernameFormSession(session));

        return new JsonResult<User>(OK, data);
    }

    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFormSession(session);
        iUserService.changePassword(uid, username, oldPassword, newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("get_by_id")
    public JsonResult<User> getByUid(HttpSession session) {
        User data = iUserService.getUserById(getUidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(HttpSession session, User user) {
        //user对象中有四部分数据，username phone email gender
        //uid需要再次封装进user对象中
        Integer uid = getUidFromSession(session);
        String username = getUsernameFormSession(session);
        iUserService.changeInfo(uid, username, user);
        return new JsonResult<>(OK);
    }

    /**
     * 设置上传文件的最大值
     */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    /**
     * MultipartFile接口是SpringMvc提供的一个接口，这个接口为我们包装了
     * 获取文件类型的数据（任何类型的file都可以接收），Springboot又整合了
     * SpringMVC，只需要在处理请求的方法参数上声明一个参数类型为MultipartFile的参数，
     * 然后springboot自动将传递给服务的文件数据赋值给这个参数
     *
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file) {
        //判断文件类型是否为null
        if (file.isEmpty()) {
            throw new FileEmptyException("文件为空");
        }
        //判断文件大小
        if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件大小超出限制");
        }
        //判断文件类型
        String contextType = file.getContentType();
        //判断文件类型
        if (!AVATAR_TYPE.contains(contextType)) {
            throw new FileTypeException("文件类型不支持");
        }
        //获取项目绝对路径
        String parent = session.getServletContext().getRealPath("upload");
        System.out.println(parent);//一会删掉
        //File对象指向这个路径，File是否存在
        File dir = new File(parent);
        if (!dir.exists()) {//检测目录是否存在
            dir.mkdir();//如果当前路径不存在，则创建新的目录
        }
        //获取这个文件名称，后期使用UUID工具来生成一个新的字符串作为文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("OriginalFilename" + originalFilename);//删掉
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
        File dest = new File(dir, filename);//在dir目录下创建一个新的文件。空的！！
        //将参数file中数据写入到这个空文件中
        try {
            file.transferTo(dest);//将file文件中的数据写入到dest中
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadException("文件读写异常");
        }

        Integer uid = getUidFromSession(session);
        String username = getUsernameFormSession(session);
        //返回头像的路径/upload/test.png
        String avatar = "/upload/" + filename;
        iUserService.changeAvatar(uid,avatar,username);
        //返回用户头像的路径给前端页面，将来用于头像的展示使用
        return new JsonResult<>(OK,avatar);
    }


//    @RequestMapping("reg")
//    public JsonResult<Void> reg(User user){
//        //创建响应结果对象
//        JsonResult<Void> result = new JsonResult<>();
//        try {
//            iUserService.reg(user);
//            result.setState(200);
//            result.setMessage("用户注册成功");
//        } catch (UsernameDuplicatedException e) {
//            result.setState(4000);
//            result.setMessage("用户名被占用");
//        } catch (InsertException e){
//            result.setState(5000);
//            result.setMessage("用户名被占用");
//        }
//        return result;
//    }
}
